/**
 * 942. 增减字符串匹配942. 增减字符串匹配
 * https://leetcode.cn/problems/di-string-match/
 */
const { displayBaseArray } = require('../../libs/public');

/**
 * @param {string} s
 * @return {number[]}
 */
function diStringMatch(s) {
  const length = s.length + 1;
  const indexes = new Array(length);
  let head = 0;
  let tail = length - 1;
  for (let i = 0; i < s.length; i += 1) {
    if (s[i] === 'D') {
      indexes[head] = i;
      head += 1;
    } else {
      indexes[tail] = i;
      tail -= 1;
    }
  }
  indexes[tail] = length - 1;
  tail -= 1;
  const result = new Array(s.length + 1);
  for (let i = 0, cur = length - 1; i < head; i += 1, cur -= 1) {
    result[indexes[i]] = cur;
  }
  for (let i = length - 1, cur = 0; i > tail; i -= 1, cur += 1) {
    result[indexes[i]] = cur;
  }
  return result;
}

console.log(displayBaseArray(diStringMatch('IDID')) === '[0,4,1,3,2]');
console.log(displayBaseArray(diStringMatch('III')) === '[0,1,2,3]');
console.log(displayBaseArray(diStringMatch('DDI')) === '[3,2,0,1]');
console.log(displayBaseArray(diStringMatch('D')) === '[1,0]');
console.log(displayBaseArray(diStringMatch('I')) === '[0,1]');
